import 'package:asperm/tools/storage.dart';
import 'package:flutter/material.dart';
 import 'dart:ui' as ui;



class LanguageProvider with ChangeNotifier {
  Locale _currentLocale = const Locale('en', 'US');

  Locale get currentLocale => _currentLocale;

  initialize() {

    String? languageCode = SpUtil.preferences.getString('languageCode');
    String? countryCode = SpUtil.preferences.getString('countryCode');
    if (languageCode != null && countryCode != null) {

      print('-----languageCode----------:${languageCode}');
      print('-----countryCode----------:${countryCode}');

      _currentLocale = Locale(languageCode, countryCode);

      // _currentLocale = Locale('en', "US");
      // changeLanguage(Locale('en', "US"));
    } else{
      Locale systemLocale = ui.PlatformDispatcher.instance.locale;
      String lanCode = systemLocale.languageCode;
      String couCode = systemLocale.countryCode!;
      _currentLocale = Locale(lanCode, couCode);
      if(lanCode == 'zh'){
        changeLanguage(Locale('zh', 'CN'));
      }else if(lanCode == 'es'){
        changeLanguage(Locale('es', 'ES'));
      }else {
        changeLanguage(Locale('en', "US"));
      }

      print('系统 lanCode----------:${lanCode}');
      print('系统 couCode----------:${couCode}');

      // _currentLocale = Locale('en', "US");
      // changeLanguage(Locale('en', "US"));


    }
    notifyListeners();
  }

  changeLanguage(Locale newLocale) {
    _currentLocale = newLocale;
    SpUtil.preferences.setString('languageCode', newLocale.languageCode);
    SpUtil.preferences.setString('countryCode', newLocale.countryCode!);
    notifyListeners();
  }

  getCurrentLanguage() {

    String? languageCode = SpUtil.preferences.getString('languageCode');
    String? countryCode = SpUtil.preferences.getString('countryCode');
    if (languageCode == null) {
      languageCode = 'en';
      countryCode = 'US';
    }
    return Locale(languageCode , countryCode);
  }

  bool currenLanguageIsCN() {
    Locale locale = getCurrentLanguage();
    if (locale.countryCode == 'CN') {
      return true;
    } else {
      return false;
    }
  }
}
